#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2025 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import logging
import re
import json
from utils import utils_data, ErrorInfoBuilder

logger = logging.getLogger('my_logger')


def check_signature():
    file_entities = utils_data.get_file()
    if not file_entities:
        logger.error("未获取到文件信息")
        return

    has_error = False

    apl_regex = re.compile(r'"apl":"([^"]+)"')
    app_feature_regex = re.compile(r'"app-feature":"([^"]+)"')

    for file_entity in file_entities:
        if file_entity.file_name.endswith(".p7b"):
                with open(file_entity.full_path, 'r', encoding='utf-8', errors='ignore') as file:
                    sig_data = file.read()

                apl_match = apl_regex.search(sig_data)
                app_feature_match = app_feature_regex.search(sig_data)

                if apl_match and app_feature_match:
                    apl_value = apl_match.group(1)
                    app_feature_value = app_feature_match.group(1)

                    if apl_value == "normal" and app_feature_value == "hos_normal_app":
                        pass
                    else:
                        error_info = ErrorInfoBuilder() \
                            .set_buggy_file_path(file_entity.file_path) \
                            .set_defect_type("XTS.CHECK.SIGNATURE.01") \
                            .set_description("签名证书级别不符合XTS规范") \
                            .set_main_buggy_line(0) \
                            .set_main_buggy_code(f"'apl'='{apl_value}','app-feature'='{app_feature_value}'") \
                            .build()

                        utils_data.write_error_to_json_file(error_info)
                        logger.info(json.dumps(error_info, indent=4, ensure_ascii=False))
                        has_error = True
                else:
                    error_info = ErrorInfoBuilder() \
                        .set_buggy_file_path(file_entity.file_path) \
                        .set_defect_type("XTS.CHECK.SIGNATURE.01") \
                        .set_description("签名证书级别不符合XTS规范") \
                        .set_main_buggy_line(0) \
                        .set_main_buggy_code("签名证书配置异常") \
                        .build()

                    utils_data.write_error_to_json_file(error_info)
                    logger.info(json.dumps(error_info, indent=4, ensure_ascii=False))
                    has_error = True

    if has_error:
        logger.info("签名证书级别检查完成，错误信息已写入xts_result.json")
    else:
        logger.info("签名证书级别检查通过")
